package net.zoneland.zrdp.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;


/**
 * Repeatable 过滤器，如果request 是APPLICATION_JSON_VALUE的时候构建可以重复读取的request。
 * 系统框架判断是否重复提交的时候会先读取一次body中的数据（见SameUrlDataInterceptor），后面正常处理需要可重复读取。
 * @author zonevue
 */
public class RepeatableFilter implements Filter {

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {

        if (request instanceof HttpServletRequest &&
            StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {

            final ServletRequest requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request);
            chain.doFilter(requestWrapper, response);

        } else {
            chain.doFilter(request, response);
        }

    }

}
